package com.zhkj.crawl.rank.ext;

import com.zhkj.crawl.config.StringPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverLogLevel;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

@Slf4j
public class BaseChromeOpt {
    public static final boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win");


    public static void toPage(ChromeDriver driver, String url){
        driver.get(url);
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
    }

    public static ChromeDriver initDriver(boolean needProxy) {
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setLogLevel(ChromeDriverLogLevel.OFF);
        if(!isWindows){
            chromeOptions.addArguments("-headless");
        }
        chromeOptions.addArguments("--silent");
        chromeOptions.addArguments("log-level=3");
        chromeOptions.addArguments("--disable-blink-features=AutomationControlled");
        chromeOptions.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));

        if(needProxy){
            String proxyServer = "127.0.0.1:1087";
            String[] paris = proxyServer.split(StringPool.COLON);
            Proxy proxy = new Proxy()
                    .setHttpProxy(paris[0])
                    .setSslProxy(paris[1]);
            chromeOptions.setProxy(proxy);
//            chromeOptions.addArguments("load-extension=D:\\data\\logistics-group\\crawl-service\\src\\main\\resources\\proxyExtension");
        }

        ChromeDriver chromeDriver = new ChromeDriver(chromeOptions);
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("source", " Object.defineProperty(navigator, 'webdriver', {\n" +
                "      get: () => undefined\n" +
                "    })");
        chromeDriver.executeCdpCommand("Page.addScriptToEvaluateOnNewDocument", parameters);

        return chromeDriver;
    }

    public static void sleep(Integer second){
        try {
            TimeUnit.SECONDS.sleep(second);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void screenshot(ChromeDriver driver) {
        //调用截图方法 ,指定了OutputType.FILE做为参数传递给getScreenshotAs()方法，其含义是将截取的屏幕以文件形式返回
        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        String name = "selenium-" + RandomStringUtils.randomAlphanumeric(6) + ".jpg";
        try {
            FileUtils.copyFile(srcFile, new File("D:\\" + name + ""));
        } catch (IOException e) {
            log.error("截图错误", e);
        }
    }


    static {
        Logger.getLogger("org.openqa.selenium").setLevel(Level.OFF);
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        if (isWindows) {
            System.setProperty("webdriver.chrome.driver", "D:\\Program Files\\chromedriver_91_0_4472_101.exe");
        }
    }
}
